<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item prop="roleName">
        <template #label>
          <span class="font-bold">角色名称</span>
        </template>
        <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            @keyup.enter="handleQuery"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="roleKey">
        <template #label>
          <span class="font-bold">权限字符</span>
        </template>
        <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            @keyup.enter="handleQuery"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <template #label>
          <span class="font-bold">角色状态</span>
        </template>
        <el-select v-model="queryParams.status" placeholder="菜单状态" clearable>
          <el-option label="启用" :value="false"/>
          <el-option label="停用" :value="true"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery" @keyup.enter="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-button type="primary" plain @click="handleAdd">
      <el-icon><Plus /></el-icon>
      新增
    </el-button>
    <el-button type="danger" plain @click="handleDelete" :disabled="multipleSelection.length == 0">
      <el-icon><Delete /></el-icon>
      批量删除
    </el-button>
  </div>

  <el-scrollbar>
    <el-table :data="tableData" fit
              v-loading="loading"
              table-layout="auto"
              style="width: 100%; margin-top: 15px;"
              :header-cell-style="{ background:'#eee','text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roleId" label="角色编号" width="100" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="roleKey" label="权限字符"  />
      <el-table-column prop="roleSort" label="显示顺序"  />
      <el-table-column prop="status" label="角色状态" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              inline-prompt
              active-text="正常"
              inactive-text="停用"
              :active-value="false"
              :inactive-value="true"
              @change="handleSwitch(scope.row.roleId)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" plain size="small" text @click="handleEdit(scope.row.roleId)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button type="danger" plain size="small" text @click="handleDelete(scope.row.roleId)" >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="getPageList"
          @current-change="getPageList"
      />
    </div>
  </el-scrollbar>


  <!--  新增菜单弹出框-->
  <el-dialog
      v-model="centerDialogVisible"
      :title="dialogTitle"
      width="30%"
      top="10vh"
      @close="onCloseDialog"
      @open="onOpenDialog"
  >
    <el-form :model="role" ref="roleForm" label-position="right"  label-width="100px" :rules="rules" size="large">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="roleName">
            <template #label>
              <span class="font-bold">角色名称</span>
            </template>
            <el-input v-model="role.roleName" placeholder="请输入角色名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="roleKey">
            <template #label>
              <span class="font-bold">权限字符</span>
            </template>
            <el-input v-model="role.roleKey" placeholder="权限字符" clearable />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="roleSort">
            <template #label>
              <span class="font-bold">角色排序</span>
            </template>
            <el-input-number v-model="role.roleSort" controls-position="right" :min="0" style="width: 60%"/>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="status">
            <template #label>
              <span class="font-bold">角色状态</span>
            </template>
            <el-radio-group v-model="role.status">
              <el-radio :label="false">启用</el-radio>
              <el-radio :label="true">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="roleKey">
            <template #label>
              <span class="font-bold">备注</span>
            </template>
            <el-input v-model="role.remark" type="textarea" placeholder="请输入备注" clearable />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item prop="menuIds">
            <template #label>
              <span class="font-bold">菜单权限</span>
            </template>
            <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
            <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>

<!--            <el-tree v-model="role.menuIds" :data="menuOptions" check-strictly style="width: 100%" />-->
            <el-tree
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                ref="menu"
                node-key="id"
                :check-strictly="!menuCheckStrictly"
                :default-checked-keys="role.menuIds"
                empty-text="加载中，请稍候"
                :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button type="info" @click="onCancel" style="margin-right: 10%">取消</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import {onMounted, ref, reactive, defineEmits,nextTick} from "vue";
import {addRoleAndMenus, changeStatus, deleteRole, getRoleAndMenus, getRoleList, updateRoleAndMenus} from '@/api/role.js'
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {addMenu, getIcons, getMenu, getMenuTreeSelect, updateMenu} from "@/api/menu.js";

const emit = defineEmits(['hidden','show']) //未用到，加上解决警告，问题在哪不知道
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogTitle = ref('新增角色')
const centerDialogVisible = ref(false)
const multipleSelection = ref([])
const menuOptions = ref([])
const menu = ref(null)
const roleForm = ref(null)
const menuExpand = ref(false)
const menuNodeAll = ref(false)
const menuCheckStrictly = ref(true)
const role = reactive(defaultValue())
function defaultValue(){
  return {
    roleId: null,
    roleName: null,
    roleKey: null,
    roleSort: null,
    status: false,
    remark: null,
    menuIds: [],
  }
}
const queryParams = reactive({
  roleName: null,
  roleKey: null,
  status: null,
})
const defaultProps = {
  children: "children",
  label: "label"
}
const rules = {
  roleName: [
    {required: true, message: '角色名称不能为空', trigger: 'blur'},
  ],
  roleKey: [
    {required: true, message: '权限字符不能为空', trigger: 'blur'},
  ],
  roleSort: [
    {required: true, message: '角色顺序不能为空', trigger: 'blur'},
  ],
}


onMounted(() =>{
  getPageList()
})

async function getPageList(){
  loading.value = true
  await getRoleList(currentPage.value, pageSize.value,queryParams).then(res =>{
    tableData.value = res.data.records;
    total.value = res.data.total;
  })
  loading.value = false
}

function handleQuery(){
  getPageList()
}
function resetQuery(){
  queryParams.roleName = null
  queryParams.roleKey = null
  queryParams.status = null
  handleQuery()
}
function handleSelectionChange(val){
  multipleSelection.value = val
}
function handleSwitch(id){
  changeStatus(id).then(res =>{
    getPageList()
    ElMessage.success(res.msg)
  }).catch(err =>{
    getPageList()
  })
}
function reset(){
  Object.assign(role,defaultValue())
}
function handleAdd(){
  reset()
  dialogTitle.value = '新增角色'
  centerDialogVisible.value = true
}
async function handleEdit(id){
  centerDialogVisible.value = true
  dialogTitle.value = '修改角色信息'
  await getRoleAndMenus(id).then(res =>{
    role.roleId = res.data.roleId
    role.roleName = res.data.roleName
    role.roleKey = res.data.roleKey
    role.roleSort = res.data.roleSort
    role.status = res.data.status
    role.remark = res.data.remark
    console.log(menu.value)
    res.data.menus.forEach(v => {
      console.log(v.menuId);
      menu.value.setChecked(v.menuId, true, false);
    })
  })
}

function onOpenDialog(){
  if(menuOptions.value.length == 0){
    getMenuTreeSelect().then(res => {
      menuOptions.value = res.data
    })
  }
}
function onCloseDialog(){
  menu.value.setCheckedNodes([]);
  centerDialogVisible.value = false
}

function onSubmit(){
  role.menuIds = getMenuAllCheckedKeys()
  roleForm.value.validate(valid => {
    if (valid) {
      if (role.roleId != null) {
        updateRoleAndMenus(role).then(res => {
          ElMessage.success(res.msg);
          onCancel();
          getPageList();
        })
      } else {
        addRoleAndMenus(role).then(res => {
          ElMessage.success(res.msg);
          onCancel();
          getPageList();
        })
      }
      menuOptions.value = []
    }
  })
}
function onCancel(){
  reset()
  centerDialogVisible.value = false
}
function handleDelete(id) {
  let ids = multipleSelection.value.length != 0 ? multipleSelection.value.map(item => item.roleId) : id;
  ElMessageBox.confirm('此操作将永久删除编号为' + ids +'的角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteRole(ids).then(res =>{
      ElMessage.success(res.msg)
    })
  })
}
// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menu.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menu.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
function handleCheckedTreeExpand(value,) {
    let treeList = menuOptions.value
    for (let i = 0; i < treeList.length; i++) {
      menu.value.store.nodesMap[treeList[i].id].expanded = value;
    }
}
// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value) {
    menu.value.setCheckedNodes(value ? menuOptions.value: []);
}
// 树权限（父子联动）
function handleCheckedTreeConnect(value) {
    menuCheckStrictly.value = value ? true: false;
}
</script>

<style scoped>
.font-bold{
  font-weight: bold;
}
.pagination{
  padding: 20px 0;
  margin-left:55%;
  transform: translate(-50%,0);
}
.tree-border{
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius:4px;
  width: 100%;
}
</style>
